from flask import Flask, render_template, request, send_file, jsonify
import os

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'outputs'

# 确保输出目录存在
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)

@app.route('/')
def index():
    return render_template('index.html')

# 文件处理路由
@app.route('/file/stats', methods=['POST'])
def file_stats():
    file_path = request.form.get('file_path')
    if not file_path:
        return jsonify({'error': '请提供文件路径'})
    
    if not os.path.exists(file_path):
        return jsonify({'error': '文件不存在'})
    
    from file_stats import get_file_stats
    stats = get_file_stats(file_path)
    return jsonify(stats)

@app.route('/file/batch-rename', methods=['POST'])
def batch_rename():
    dir_path = request.form.get('dir_path')
    prefix = request.form.get('prefix', '')
    suffix = request.form.get('suffix', '')
    
    if not dir_path:
        return jsonify({'error': '请提供目录路径'})
    
    if not os.path.exists(dir_path) or not os.path.isdir(dir_path):
        return jsonify({'error': '目录不存在或不是有效目录'})
    
    from batch_rename import rename_files
    rename_files(dir_path, prefix, suffix)
    return jsonify({'message': '文件重命名完成'})

@app.route('/file/find-duplicates', methods=['POST'])
def find_duplicates():
    dir_path = request.form.get('dir_path')
    if not dir_path:
        return jsonify({'error': '请提供目录路径'})
    
    if not os.path.exists(dir_path) or not os.path.isdir(dir_path):
        return jsonify({'error': '目录不存在或不是有效目录'})
    
    from find_duplicate_files import find_duplicate_files
    duplicates = find_duplicate_files(dir_path)
    return jsonify({'duplicates': duplicates})

@app.route('/file/search', methods=['POST'])
def search_files():
    dir_path = request.form.get('dir_path')
    pattern = request.form.get('pattern')
    
    if not dir_path or not pattern:
        return jsonify({'error': '请提供目录路径和搜索模式'})
    
    if not os.path.exists(dir_path) or not os.path.isdir(dir_path):
        return jsonify({'error': '目录不存在或不是有效目录'})
    
    from search_files import search_files_in_dir
    results = search_files_in_dir(dir_path, pattern)
    return jsonify({'results': results})

# 图片处理路由
@app.route('/image/extract-text', methods=['POST'])
def extract_text_from_image():
    image_path = request.form.get('image_path')
    use_ai = request.form.get('use_ai', 'false').lower() == 'true'
    
    if not image_path:
        return jsonify({'error': '请提供图片路径'})
    
    if not os.path.exists(image_path):
        return jsonify({'error': '图片不存在'})
    
    if use_ai:
        from image_to_text_ai import extract_text
    else:
        from image_to_text import extract_text
    
    text = extract_text(image_path)
    return jsonify({'text': text})

# 文件处理路由
@app.route('/file/organize', methods=['POST'])
def organize_files():
    source_dir = request.form.get('source_dir')
    if not source_dir:
        return jsonify({'error': '请提供源文件目录路径'})
    
    if not os.path.exists(source_dir) or not os.path.isdir(source_dir):
        return jsonify({'error': '源文件目录不存在或不是有效目录'})
    
    
    # 调用文件组织器
    from file_organizer import classify_files
    classify_files(source_dir)
    
    return jsonify({'message': '文件已成功组织'})

# Excel处理路由
@app.route('/excel/clean', methods=['POST'])
def clean_excel():
    input_path = request.form.get('file_path')
    if not input_path:
        return jsonify({'error': '请提供Excel文件路径'})
    
    if not os.path.exists(input_path) or not os.path.isfile(input_path):
        return jsonify({'error': '文件不存在或不是有效文件'})
    
    if not input_path.endswith('.xlsx'):
        return jsonify({'error': '不支持的文件格式，仅支持.xlsx格式'})
    
    filename = os.path.basename(input_path)
    output_path = os.path.join(app.config['UPLOAD_FOLDER'], 'cleaned_' + filename)
    
    # 调用Excel清洗器
    from excel.data_cleaner import clean_data
    clean_data(input_path, output_path)
    
    return send_file(output_path, as_attachment=True)

@app.route('/excel/summary', methods=['POST'])
def summarize_excel():
    input_path = request.form.get('file_path')
    if not input_path:
        return jsonify({'error': '请提供Excel文件路径'})
    
    if not os.path.exists(input_path) or not os.path.isfile(input_path):
        return jsonify({'error': '文件不存在或不是有效文件'})
    
    if not input_path.endswith('.xlsx'):
        return jsonify({'error': '不支持的文件格式，仅支持.xlsx格式'})
    
    filename = os.path.basename(input_path)
    output_path = os.path.join(app.config['UPLOAD_FOLDER'], 'summary_' + filename)
    
    # 调用Excel汇总工具
    from excel.data_summary import summarize_data
    summarize_data(input_path, output_path)
    
    return send_file(output_path, as_attachment=True)

# PDF处理路由
@app.route('/pdf/to-text', methods=['POST'])
def pdf_to_text():
    input_path = request.form.get('file_path')
    if not input_path:
        return jsonify({'error': '请提供PDF文件路径'})
    
    if not os.path.exists(input_path) or not os.path.isfile(input_path):
        return jsonify({'error': '文件不存在或不是有效文件'})
    
    if not input_path.endswith('.pdf'):
        return jsonify({'error': '不支持的文件格式，仅支持.pdf格式'})
    
    from pdf.pdf_to_text import extract_text
    text = extract_text(input_path)
    return jsonify({'text': text})

@app.route('/pdf/to-image', methods=['POST'])
def pdf_to_image():
    input_path = request.form.get('file_path')
    use_imagemagick = request.form.get('use_imagemagick', 'false').lower() == 'true'
    
    if not input_path:
        return jsonify({'error': '请提供PDF文件路径'})
    
    if not os.path.exists(input_path) or not os.path.isfile(input_path):
        return jsonify({'error': '文件不存在或不是有效文件'})
    
    if not input_path.endswith('.pdf'):
        return jsonify({'error': '不支持的文件格式，仅支持.pdf格式'})
    
    output_dir = os.path.join(app.config['UPLOAD_FOLDER'], 'pdf_images')
    os.makedirs(output_dir, exist_ok=True)
    
    if use_imagemagick:
        from pdf.pdf_to_image_ImageMagick import convert_pdf_to_images
    else:
        from pdf.pdf_to_image import convert_pdf_to_images
    
    image_paths = convert_pdf_to_images(input_path, output_dir)
    return jsonify({'image_paths': image_paths})

@app.route('/pdf/extract-invoice', methods=['POST'])
def extract_invoice():
    input_path = request.form.get('file_path')
    if not input_path:
        return jsonify({'error': '请提供PDF文件路径'})
    
    if not os.path.exists(input_path) or not os.path.isfile(input_path):
        return jsonify({'error': '文件不存在或不是有效文件'})
    
    if not input_path.endswith('.pdf'):
        return jsonify({'error': '不支持的文件格式，仅支持.pdf格式'})
    
    filename = os.path.basename(input_path)
    output_path = os.path.join(app.config['UPLOAD_FOLDER'], 'invoice_' + filename.replace('.pdf', '.xlsx'))
    
    # 调用PDF发票提取器
    from pdf.pdfplumber_extractor import extract_invoice_data
    extract_invoice_data(input_path, output_path)
    
    return send_file(output_path, as_attachment=True)

@app.route('/pdf/office-to-pdf', methods=['POST'])
def office_to_pdf():
    input_path = request.form.get('file_path')
    if not input_path:
        return jsonify({'error': '请提供Office文件路径'})
    
    if not os.path.exists(input_path) or not os.path.isfile(input_path):
        return jsonify({'error': '文件不存在或不是有效文件'})
    
    supported_extensions = ('.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx')
    if not input_path.lower().endswith(supported_extensions):
        return jsonify({'error': '不支持的文件格式，仅支持Office文档格式'})
    
    filename = os.path.basename(input_path)
    output_path = os.path.join(app.config['UPLOAD_FOLDER'], filename.rsplit('.', 1)[0] + '.pdf')
    
    # 调用Office转PDF工具
    from pdf.office_to_pdf import convert_to_pdf
    convert_to_pdf(input_path, output_path)
    
    return send_file(output_path, as_attachment=True)

if __name__ == '__main__':
    app.run(debug=True, port=5000)